package com.neuedu.it.newidea.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.it.newidea.po.Creation;
import com.neuedu.it.newidea.po.User;
import com.neuedu.it.newidea.service.CreationService;
import com.neuedu.it.newidea.web.dto.RespEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;


import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@RestController
@CrossOrigin
public class CreationController {
    @Autowired
    private CreationService creationService;
    @Value("${my.img_dir}")
    private String imgDir = null;
    @Autowired
    private ObjectMapper objectMapper;
    private static final Logger logger = LoggerFactory.getLogger(CreationController.class);


    public String saveImageFromUrl(String imageUrl, String dir) throws IOException {
        // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建HTTP GET请求
            HttpGet httpGet = new HttpGet(imageUrl);
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
                // 检查响应状态
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    // 获取响应体
                    HttpEntity entity = response.getEntity();
                    byte[] imageBytes = EntityUtils.toByteArray(entity);
                        // 生成文件名
                    String fileName = imageUrl.split("\\?")[0].substring(imageUrl.lastIndexOf("/") + 1);
                        // 保存图片
                    Path imagePath = Paths.get(dir, fileName);
                    Files.write(imagePath, imageBytes);
                    return fileName;
                }
                return null;
            } finally {
                // 关闭响应
                response.close();
                httpClient.close();
            }
    }

    @PostMapping("/creation/publish")
    public RespEntity pulish(HttpServletRequest request, Creation creation, MultipartFile pic, String ai_img_url) throws IOException {
       User user=(User) request.getAttribute("curUser");
       creation.setUserId(user.getId());
        String dir=this.imgDir;
        File dirFile=new File(dir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        if(!ai_img_url.isEmpty()){
            String fileName=saveImageFromUrl(ai_img_url,dir);
            creation.setImg(fileName);
        }
        else if(!pic.isEmpty()){
            String fileName=new Date().getTime()+"_"+pic.getOriginalFilename();
            pic.transferTo(new File(dir+"\\"+ fileName));//把图片统一保存在某个目录
            creation.setImg(fileName);//把图片的路径保存到数据库去
        }
        creation.setClick(0);
        creation.setCreateTime(new Date());
        creationService.save(creation);
        return new RespEntity("2000", "发布成功", creation);
    }

    @RequestMapping("/creation/list")
    public RespEntity list(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum
            ,@RequestParam(value = "pageSize", defaultValue = "10") int pageSize
            ,@RequestParam(value = "search", defaultValue = "")String search) {
        Page<Creation> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Creation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(!search.isEmpty(),Creation::getTitle, search)
                .or().like(!search.isEmpty(),Creation::getContent, search)
                .orderByDesc(Creation::getCreateTime)
                .orderByDesc(Creation::getCreateTime);
        creationService.page(page,queryWrapper);
        return new RespEntity("2000","查询成功",page);
    }
    // 获取创作详情（用于编辑）
    @GetMapping("/creation/detail/{id}")
    public RespEntity detail(
            @PathVariable("id") Integer id) {
        Creation creation = creationService.getById(id);
        creation.setClick(creation.getClick()+1);
        creationService.updateById(creation);
        System.out.println(creation);
        return new RespEntity("2000", "获取成功", creation);
    }

    @PostMapping("/creation/saveimg")
    public RespEntity saveImg(HttpServletRequest request,
                              @RequestParam String title,
                              @RequestParam String keyword,
                              @RequestParam String ai_img_response) throws IOException {

        User user = (User) request.getAttribute("curUser");
        logger.info("开始处理AI图片保存请求，用户ID: {}", user.getId());

        // 检查响应数据是否为空
        if (ai_img_response == null || ai_img_response.trim().isEmpty()) {
            return new RespEntity("4001", "响应数据为空", null);
        }

        // 解析阿里云返回的JSON响应
        JsonNode responseNode;
        try {
            responseNode = objectMapper.readTree(ai_img_response);
        } catch (Exception e) {
            logger.error("响应格式解析错误", e);
            return new RespEntity("4002", "响应格式错误", null);
        }

        // 检查响应状态
        if (!responseNode.has("output") || !responseNode.get("output").has("task_status") ||
                !"SUCCEEDED".equals(responseNode.get("output").get("task_status").asText())) {
            return new RespEntity("4003", "图片生成未完成或失败", null);
        }

        // 提取图片URL列表
        List<String> imgUrls = new ArrayList<>();
        JsonNode resultsNode = responseNode.get("output").get("results");
        if (resultsNode != null && resultsNode.isArray()) {
            for (JsonNode resultNode : resultsNode) {
                if (resultNode.has("url")) {
                    imgUrls.add(resultNode.get("url").asText());
                }
            }
        }

        logger.info("提取到 {} 个图片URL", imgUrls.size());

        if (imgUrls.isEmpty()) {
            return new RespEntity("4004", "未找到图片URL", null);
        }

        String dir = this.imgDir;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        List<String> savedFileNames = new ArrayList<>();
        for (String url : imgUrls) {
            try {
                String fileName = saveImageFromUrl(url, dir);
                if (fileName == null) {
                    logger.warn("图片下载失败: " + url);
                    continue;
                }
                savedFileNames.add(fileName);
            } catch (Exception e) {
                logger.error("下载图片时发生错误: " + url, e);
            }
        }

        // 检查是否至少成功下载了一张图片
        if (savedFileNames.isEmpty()) {
            return new RespEntity("4005", "所有图片下载失败", null);
        }

        logger.info("成功保存 {} 张图片", savedFileNames.size());

        Creation creation = new Creation();
        creation.setUserId(user.getId());
        creation.setTitle(title);
        creation.setKeyword(keyword);
        creation.setCgyId(4); // 4表示图片创作
        creation.setContent(objectMapper.writeValueAsString(savedFileNames)); // 图片名称列表的JSON字符串
        creation.setImg(savedFileNames.get(0)); // 第一张图片作为封面
        creation.setClick(0);
        creation.setCreateTime(new Date());

        creationService.save(creation);

        return new RespEntity("2000", "保存成功", creation);
        
        }
}
